<?php
namespace backend\controllers;

use Yii;
use backend\controllers\BaseController;
use yii\data\Pagination;
use yii\web\UploadedFile;
use backend\models\course\Course;
use backend\models\course\CourseForm;
use backend\models\course\CourseType;
use backend\models\course\Qusetion;
use backend\models\course\CourseRank;
use backend\models\course\CourseSource;
use backend\models\course\CourseCategory;
use backend\models\course\Comment;
use backend\models\Teacher;
use backend\models\course\Question;
use backend\models\course\User;
use backend\models\course\CourseSection;
use backend\models\course\CoursePeriod;
use backend\models\course\CourseJoint;
use common\components\Ftp;
/**
 * 课程功能模块
 * @author 解科
 */
class CourseController extends BaseController
{
	/**
	* @inheritdoc  课程展示
	*/
	public function actionIndex()
	{

		$session = Yii::$app->session;
		if(!empty(Yii::$app->request->get('page'))){
			$session->open();
			$coursesearch=$session->get('coursesearch');
			$cond=$session->get('cond');
		}else{
			$course = Yii::$app->request->post();
			//搜索条件
			$cond = ['and'];
            if(!empty($course)){
			if($course['coursetype']) 			 $cond[] = ['=','edu_course.type_id',$course['coursetype']];
			if($course['status']) 				 $cond[] = ['=','status',$course['status']];
			if($course['status'] == "0") 		 $cond[] = ['=','status',$course['status']];
			if($course['Course']['course_name']) $cond[] = ['like','course_name',$course['Course']['course_name']];
			if($course['user_name']) 			 $cond[] = ['like','teacher_name',$course['user_name']];
			$coursesearch = $course;
			$session->open();
			$session->set('coursesearch', $coursesearch);
			$session->set('cond', $cond);
			}else{
			  $coursesearch =array('coursetype'=>'');
			  $coursesearch['status']='';
			  $coursesearch['Course']['course_name']='';
			  $coursesearch['user_name']='';
			}
		}
        
		$model = new Course();
		$pagination = new Pagination([
			'defaultPageSize' => 15,
			'totalCount' => $model->CourseCount($cond),
		]);
		$data = $model->CourseSearch($cond,$pagination);
		$CourseType = new CourseType;
		$type = $CourseType -> seltype();
		return $this->render('index',[
				'courses' => $data,
				'model' => $model,
				'pagination' => $pagination,
				'coursesearch' => $coursesearch,
				'type' => $type,
		]);
	}
    /**
     * @inheritdoc  课程创建
     */

    public function actionCreate()
    {
        $model = new Course;
        if (Yii::$app->request->post()) {

           $model->course_name = Yii::$app->request->post('title');
           $model->teacher_id = 15;   //暂时写死
           $model->add_time = time();
           $model->upd_time = time();
           $re = $model->save();
           $id = Yii::$app->db->getLastInsertID();
           if ($id) {
               return $this->redirect(array('/course/edit','id'=>$id,'type'=>'base'));
           }
        }
        return $this->render('manage/create');
    }

    /**
     * @inheritdoc  编辑课程
     */
    public function actionEdit()
    {
		$request  = YII::$app->request;
		$id       = $request->get('id');  //id 为课程id
		$model    = Course::find()->where(['course_id'=>$id])->with('teacher')->asArray()->one();
		//判断是否有表单提交
		if (Yii::$app->request->ispost) {
			//执行添加/编辑 章
    		if (Yii::$app->request->post('type') =="add_section") {
    			$course_id = Course::SectionAdd();
    			return $this->redirect(array('/course/edit','id'=>$course_id,'type'=>'lesson'));
    		}

    		//执行添加/编辑 节
    		if (Yii::$app->request->post('type') =="add_joint") {
    			$course_id = Course::JointAdd();
    			return $this->redirect(array('/course/edit','id'=>$course_id,'type'=>'lesson'));
    		}

    		//执行添加 课时
    		if (Yii::$app->request->post('type') =="add_period") {
    			$data         = Yii::$app->request->post();

    			$course_id = Course::PeriodAdd();

    			return $this->redirect(array('/course/edit','id'=>$course_id,'type'=>'lesson'));
    		}
    		//如果无类型判断 默认执行课程修改
			$model = new Course;
			$id    = $request -> post('course_id');
			$model = $model   -> findOne($id);
			$aa    = $model   -> setAttributes(Yii::$app->request->post());
			$re    = $model   -> validate();

    		if (!$re) {
    			echo "数据错误";die;
    		}
			$re    = $model->save();

    	}
    	//编辑课程详情页
    	if ($request->get('type')=='detail') {
    		$Course 	 = Course::findOne($id);
    		return $this->render('manage/detail',['course' =>$model,'model'=>$Course]);
    	}
    	//编辑课程封面
    	if ($request->get('type')=='picture') {
			$Course 	 = new Course;
    		return $this->render('manage/picture',[
				'course' => $model,
				'model'  => $Course,
			]);
    	}
		//编辑课程封面
    	if ($request->get('type')=='student') {
			$Course 	 = new Course;
    		return $this->render('manage/student',[
				'course' => $model,
				'model'  => $Course,
			]);
    	}
    	//编辑课程价格
    	if ($request->get('type')=='price') {
			$Course 	 = new Course;
    		return $this->render('manage/price',[
				'course' => $model,
				'model'  => $Course,
			]);
    	}

    	////编辑课程课时
    	if ($request->get('type')=='lesson') {
    		//获取课程目录
    		$section       = Course::CourseCatalog($id);
    		$section_model = new CourseSection;
    		$joint_model   = new CourseJoint;
    		$period_model  = new CoursePeriod;
    		return $this->render('manage/lesson',[
											'course'        => $model,
											'sections'      => $section,
											'section_model' => $section_model,
											'joint_model'   => $joint_model,
											'period_model'  => $period_model,
    		]);
    	}


    	$type    = CourseType::find()->where(['is_show'=>1])->asArray()->all();
		$rank    = CourseRank::find()->where(['is_show'=>1])->asArray()->all();
		$source  = CourseSource::find()->where(['is_show'=>1])->asArray()->all();
		$cate    = CourseCategory::find()->where(['is_show'=>1])->asArray()->all();
    	return $this->render("manage/base",[
										'course' =>$model,
										'type'   =>$type,
										'rank'   =>$rank,
										'source' =>$source,
										'cate'   =>$cate
        ]);
    }
    /**
	 * 删除课程
	 * 课程发布后不可删除！！！
	 */
	public function actionCoursedel()
	{
		//接受课程id
		$id 	= YII::$app->request->get("id");
		$course = Course::findOne($id);
		//判断课程是否被发布过（是否以正确的方式访问）
		if ($course->status != 0) die;
		//echo $course->course_thumb;die;
		if ($course->course_thumb) {
			@unlink($course->course_thumb);
		}
		//获取章id
		$section  = CourseSection::find()->select('section_id')->where(['course_id'=>$id])->asArray()->all();
		$sections = implode(",", array_column($section,'section_id'));
    	if ($sections) {
    		//获取节id
	    	$joint  = CourseJoint::find()->select('joint_id')->where("section_id in ($sections)")->asArray()->all();
			$joints = implode(",", array_column($joint,'joint_id'));
			if ($joints) {
				//获取课时内容
				$periods =CoursePeriod::find()->select('movie_url')->where("joint_id in ($joints)")->asArray()->all();
				foreach ($periods as $k => $v) {
					if ($v['movie_url']) {
						@$re = unlink("./webupload/server/".$v['movie_url']);
					}
				}
				$re = CoursePeriod::deleteAll("joint_id in ($joints)");
			}
			$re = CourseJoint::deleteAll("section_id in ($sections)");
 			$re = CourseSection::deleteAll("course_id=$id");
    	}
    	$re=Course::deleteAll("course_id=$id");
 		if ($re) {
 				echo "1";
 			}else{
 				echo "0";
 			}

	}
	/**
	 * 发布课程
	 *
	 */
	public function actionCoursePublish()
	{
		$id = YII::$app->request->get("id");
		$course = Course::find()->where(['course_id'=>$id])->one();
		$course->status = '1';
		$re = $course->save();
		if ($re) {
			echo "1";
		}else{
			echo "0";
		}
	}

	/**
	 * 关闭课程
	 *
	 */
	public function actionCourseClose()
	{
		$id = YII::$app->request->get("id");
		$course = Course::find()->where(['course_id'=>$id])->one();
		$course->status = '2';
		$re = $course->save();
		if ($re) {
			echo "1";
		}else{
			echo "0";
		}
	}

	/**
	 *  FTP操作
	 */
	public function actionFtp()
	{
		//$ftp = new Ftp; // 打开FTP连接

		//$re= $ftp->up_file('./webupload/server/upload/'.$movie_file,'movie/'.$movie_file); // 上传文件

		//$ftp->move_file('a/b/c/cc.txt','a/cc.txt'); // 移动文件
		//$ftp->copy_file('a/cc.txt','a/b/dd.txt'); // 复制文件
		//$ftp->del_file('a/b/dd.txt'); // 删除文件
		//$ftp->del_dir('movie'); // 删除文件
		//$ftp->close(); // 关闭FTP连接
		//var_dump($re);die;
	}
	 /**
     * @inheritdoc  课程上传图片
     */
	public function actionCoursefile(){
		$model        = new Course();
		//图片上传
		$Course       = Yii::$app->request->post();
		$course_id    = $Course['Course']['course_id'];
		$course_thumb = $Course['Course']['course_thumb'];

/*		$image = UploadedFile::getInstance($model, 'course_thumb');
		$rootPath = "uploads/course/";
		$ext = $image->getExtension();
		$randName = time() . rand(1000, 9999) . "." . $ext;
		$image->saveAs($rootPath . $randName);*/

		$res=$model->CourseUpdateImg($course_id,$course_thumb);
		if($res){
			Yii::$app->getSession()->setFlash('success', '上传成功');
			return $this->redirect("index.php?r=course/edit&type=picture&id=$course_id");
		}else{
			Yii::$app->getSession()->setFlash('error', '修改失败');
			return $this->redirect("index.php?r=course/edit&type=picture&id=$course_id");
		}
		/****图片上传end***/
	}
	/**
	*  课程统计
	*/
	public function actionCount()
	{
		return $this->render('count');
	}

    /**
     * 直播管理
     */
    public function actionLive()
    {

    	$time=time();
    	$type = YII::$app->request->get('type');
    	if ($type=='opening' || empty($type)) {
    		$cond = "open_time<$time and edu_course_period.end_time>$time and open_time is not null and type_id=11";
    	}elseif ($type=='coming') {
    		$new_time = $time+3600*24*7;
    		$cond = "open_time>$time and open_time<$new_time  and open_time is not null and type_id=11";
    	}elseif ($type=='end'){
    		$cond = "edu_course_period.end_time<$time and open_time is not null and type_id=11";
    	}

    	$CoursePeriod = CoursePeriod::find()->joinwith('course')
    										->where($cond)
    										->orderBy('open_time desc')
    										->asArray()->all();

    	if (!empty($type)) {
    		return $this->renderPartial('liveajax',['periods'=>$CoursePeriod]);
    	}else{
    		return $this->render('live',['periods'=>$CoursePeriod]);
    	}

    }

    /**
     * 问答管理
     */
    public function actionQues()
    {
		//查询关于课程问答
		$model = new Question;
		$user = $model->Classs();
		$course = $model->CourseClass();
		$pagination = new Pagination([
            'defaultPageSize' => 3,
            'totalCount' => Question::find()->where("ques_type=0")->count(),
        ]);
        $user = Question::find()->where("ques_type=0")
			->offset($pagination->offset)
			->limit($pagination->limit)
			->asArray()->all();
		return $this->render("ques",['name'=>$user,'course'=>$course,'pagination' => $pagination,]);
    }
	//问答管理->课程问答
	public function actionClassques(){
		$request = Yii::$app->request;
		if($request->get('ques_type')==0){
			//查询关于课程问答
			$model = new Question;
			$user = $model -> Classs();
			$course = $model ->CourseClass();
			$pagination = new Pagination([
            'defaultPageSize' => 3,
            'totalCount' => Question::find()->where("ques_type=0")->count(),
        ]);

        $user = Question::find()->where("ques_type=0")
			->offset($pagination->offset)
			->limit($pagination->limit)
			->asArray()->all();
		return $this->render("ques",['name'=>$user,'course'=>$course,'pagination' => $pagination]);
		}
		if($request->get('ques_type')==1){
			//查询关于有问必答
			$model = new Question;
			$user = $model -> ClassKing();
			$pagination = new Pagination([
            'defaultPageSize' => 3,
            'totalCount' => Question::find()->where("ques_type=1")->count(),
        ]);

        $user = Question::find()->where("ques_type=1")
			->offset($pagination->offset)
			->limit($pagination->limit)
			->asArray()->all();

			return $this->render("quesanswer",["name"=>$user,'pagination' => $pagination]);
		}
	}
	/*
	*删除课程问答
	*/
	public function actionClassdel(){
		$request = Yii::$app->request;
		$id = $request->post("id");
		$id = trim($id,',');
		$model = new Question();
		$res = $model->Classdel($id);
		if($res){
			echo 1;
		}else{
			echo 0;
		}
	}
   /**
	* 搜索课程
	*/
	public $enableCsrfValidation = false;
	public function actionClasssel(){
		//搜索作者
		//开启session
		$data = Yii::$app->request->post();
		$session = Yii::$app->session;
		if(Yii::$app->request->get("page")){
			$session->open();
			$author = $session->get('author');
			$keywords = $session->get('keywords');
			$condition = $session->get('condition');
			$hidd = $session->get('hidd');
		}else{
			$session->open();
			$author = $data['author'];
			$keywords = $data['keywords'];
			$condition = $data['condition'];
			$hidd = $data['hidd'];
			$session->set('author', $data['author']);
			$session->set('keywords', $data['keywords']);
			$session->set('condition', $data['condition']);
			$session->set('hidd', $data['hidd']);
		}
		//判断作者是否为空
		if(empty($keywords)){
			$cond = ['user_name'=>"$author"];
		}elseif(empty($author)){
			//判断是标题还是内容
			if($condition=='title'){
			$cond=['like','ques_name',"$keywords"];
				}elseif($condition=='content'){
					$cond=['like','ques_content',"$keywords"];
			}
		}else{
			if($condition=='title'){
			$cond=['and',["user_name"=>"$author"],['like','ques_name',"$keywords"]];
				}elseif($condition=='content'){
		   $cond=['and',["user_name"=>"$author"],['like','ques_content',"$keywords"]];
				}
			}
		$question = Question::find()->where($cond)->asArray()->all();
		$course = Course::find()->asArray()->all();
		//分页
			$pagination = new Pagination([
            'defaultPageSize' => 3,
            'totalCount' => Question::find()->where($cond)->count(),
        ]);
        $user = Question::find()->where($cond)
			->offset($pagination->offset)
			->limit($pagination->limit)
			->asArray()->all();
		if($hidd==1){
			return $this->render("quesanswer",['name'=>$user,'author'=>$author,'keyword'=>$keywords,'pagination'=>$pagination]);
		}else{
			return $this->render("ques",['name'=>$user,'course'=>$course,'author'=>$author,'keyword'=>$keywords,'pagination'=>$pagination]);
		}


	}
	/**
	 * 评价管理
	 */
	public function actionEvaluate()
	{
		$session = Yii::$app->session;
		$comment = Yii::$app->request->post();
		if(!empty($comment)){
		$comment_content = $comment['Comment']['comment_content'];
		$course_name =  $comment["course_name"];
		$user_name =  $comment['Comment']["user_name"];
		}else{
		$comment_content = '';
		$course_name = '';
		$user_name = '';
		
		}
		
		if(!empty(Yii::$app->request->get('page'))){
			$session->open();
			$search=$session->get('search');
			$cond=$session->get('cond');
		}else{
			$search['comment_content'] = $comment_content;
			$search['course_name'] = $course_name;
			$search['user_name'] = $user_name;
			$cond = ['and',['=','comment_type','0']];
			if($comment_content)  $cond[] = ['like','comment_content',$comment_content];
			if($user_name) $cond[] = ['like','user_name',$user_name];
			if($course_name)  $cond[] = ['like','course_name',$course_name];
			$session->open();
			$session->set('search', $search);
			$session->set('cond', $cond);
		}
		//搜索条件

		$model = new Comment;
		$pagination = new Pagination([
			'defaultPageSize' => 5,
			'totalCount' => $model->CommentCount($cond),
		]);
		$data = $model->CommentSearch($cond,$pagination);
		return $this->render('evaluate',[
			'model' => $model,
			'pagination' => $pagination,
			'data' => $data,
			'search' => $search,
        ]);
    }

	/**
	 * 删除评论
	 */
	public function actionCommentdelete(){
		$request = Yii::$app->request;
		$comment_id = $request->post("comment_id");
		$model = new Comment;
		$res=$model->CommentDelete($comment_id);
		if($res){
			$this->ajaxSuccess(1);
		}else{
			$this->ajaxError(0);
		}
	}

	/**
	 * @wwx 修改评论状态
	 */
	public function actionCommentupdate(){
		$request = Yii::$app->request;
		$comment_status = $request->post("comment_status");
		$comment_id = $request->post("comment_id");
		$model = new Comment;
		if($comment_status==1){
			$res=$model->CommentUpdate($comment_id,"0");
			if($res){
				echo "0";
			}else{
				echo "2";
			}
		}else if($comment_status==0){
			$res=$model->CommentUpdate($comment_id,"1");
			if($res){
				echo "1";
			}else{
				echo "2";
			}
		}

	}

	/**
	 * @wwx  分类管理
	 */
	public function actionType()
	{
		$model = new CourseType;
		$data=$model->seltype();
		return $this->render('type',[
			'model'=>$model,
			'data' => $data,
		]);
	}
	/**
	 * @wwx  添加分类
	 */
	public function actionTypecreate()
	{
		$model = new CourseType;
		if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->success('添加分类成功！', ['course/type']);
		} else {
            $this->error('添加分类失败！', ['course/type']);
		}
	}

	/**
	 * @wwx  删除分类
	 */
	public function actionTypedelete()
	{
		$request = Yii::$app->request;
		$type_id = $request->post("type_id");
		$model = new CourseType;
		$CourseType = $model->findOne($type_id);
		$res=$CourseType->delete();
		if($res){
			echo "1";
		}else{
			echo "0";
		}
	}
	/**
	 * @wwx  显示修改分类
	 */
	public function actionTypeupdate()
	{
		$request = Yii::$app->request;
		$model = new CourseType;
		if($request->post('type') == 'list'){
			$type_id = $request->post("type_id");
			$model = $model->findOne($type_id);
			$data = $this->renderPartial('typeupdate', ['model' => $model]);
			return $this->ajaxSuccess($data);

		}else{
			$CourseType = $request->post("CourseType");
			$type_id = $CourseType['type_id'];
			$model = $model->findOne($type_id);
			if ($model->load($request->post()) && $model->save()) {
				$this->success('修改分类成功！',['course/type']);
			} else {
				$this->error('修改失败！',['course/type']);
			}
		}

	}
	/**
	 * @wwx  来源管理
	 */
	public function actionSource()
	{
		$model = new CourseSource;
		$data  = $model->selsource();
		return $this->render('source',[
			'model'=>$model,
			'data' =>$data,
		]);
	}

	/**
	 * @wwx  添加来源
	 */
	public function actionSourcecreate()
	{
		$model = new CourseSource;
		if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->success('添加来源成功！', ['course/source']);
		} else {
            $this->error('添加来源失败！', ['course/source']);
		}
	}

	/**
	 * @wwx  删除来源
	 */
	public function actionSourcedelete()
	{
		$request = \YII::$app->request;
		$source_id = $request->post("source_id");
		$model = new CourseSource;
		$CourseSource = $model->findOne($source_id);
		$res=$CourseSource->delete();
		if($res){
			echo "1";
		}else{
			echo "0";
		}
	}
	/**
	 * @wwx  修改显示来源
	 */
	public function actionSourceupdate()
	{
		$request = Yii::$app->request;
		$model = new CourseSource;
		if($request->post('type') == 'list'){
			$source_id = $request->post("source_id");
			$model = $model->findOne($source_id);
			return $this->renderPartial('sourceupdate', ['model' => $model,]);
		}else{
			$CourseSource = $request->post("CourseSource");
			$source_id = $CourseSource['source_id'];
			$model = $model->findOne($source_id);
			if ($model->load($request->post()) && $model->save()) {
                $this->success('修改来源成功！', ['course/source']);
			} else {
                $this->error('修改来源失败！', ['course/source']);
			}
		}

	}
	/**
	 * @wwx  级别管理
	 */
	public function actionRank()
	{
		$model = new CourseRank;
		$data=$model->selrank();
		return $this->render('rank',[
			'model'=>$model,
			'data' =>$data,
		]);
	}

	/**
	 * @wwx  添加级别
	 */
	public function actionRankcreate()
	{
		$model = new CourseRank;
		if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->success('添加级别成功！', ['course/rank']);
		} else {
            $this->success('添加级别失败！', ['course/rank']);
		}
	}

	/**
	 * @wwx  删除级别
	 */
	public function actionRankdelete()
	{
		$request = Yii::$app->request;
		$rank_id = $request->post("rank_id");
		$model = new CourseRank;
		$CourseRank = $model->findOne($rank_id);
		$res=$CourseRank->delete();
		if($res){
			echo "1";
		}else{
			echo "0";
		}
	}
	/**
	 * @wwx  修改显示级别
	 */
	public function actionRankupdate()
	{
		$request = Yii::$app->request;
		$model = new CourseRank;
		if($request->post('type') == 'list'){
			$rank_id = $request->post("rank_id");
			$model = $model->findOne($rank_id);
			return $this->renderPartial('rankupdate', ['model' => $model,]);
		}else{
			$CourseRank = $request->post("CourseRank");
			$rank_id = $CourseRank['rank_id'];
			$model = $model->findOne($rank_id);
			if ($model->load($request->post()) && $model->save()){
                $this->success('修改级别成功！', ['course/rank']);
			} else {
                $this->error('修改级别失败！', ['course/rank']);
			}
		}
	}
	/**
	 * @wwx  类别管理
	 */
	public function actionCate()
	{
		$model = new CourseCategory;
		$data=$model->selcate();
		return $this->render('cate',[
			'model'=>$model,
			'data' =>$data,
		]);
	}
	/**
	 * @wwx  添加类别
	 */
	public function actionCatecreate()
	{
		$model = new CourseCategory;
		if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->success('添加类别成功！', ['course/cate']);
		} else {
            $this->error('添加失败！', ['course/cate']);
		}
	}

	/**
	 * @wwx  删除类别
	 */
	public function actionCatedelete()
	{
		$request = Yii::$app->request;
		$cate_id = $request->post("cate_id");
		$model = new CourseCategory;
		$CourseCate = $model->findOne($cate_id);
		$res=$CourseCate->delete();
		if($res){
			echo "1";
		}else{
			echo "0";
		}
	}
	/**
	 * @wwx  修改显示类别
	 */
	public function actionCateupdate()
	{
		$request = Yii::$app->request;
		$model = new CourseCategory;
		if($request->post('type') == 'list'){
			$cate_id = $request->post("cate_id");
			$model = $model->findOne($cate_id);
			return $this->renderPartial('cateupdate', ['model' => $model,]);
		}else{
			$CourseCategory = $request->post("CourseCategory");
			$cate_id = $CourseCategory['cate_id'];
			$model = $model->findOne($cate_id);
			if ($model->load($request->post()) && $model->save()) {
                $this->success('修改成功！', ['course/cate']);
			} else {
                $this->error('修改失败！', ['course/cate']);
			}
		}
	}


	/**
	 * 获取课时信息
	 */
	public function actionPeriod()
	{
		$period_id = YII::$app->request->get('period_id');
		$period = CoursePeriod::find()->where('period_id= :period_id',[":period_id"=>$period_id])->asArray()->one();
		$period['open_time'] = date("Y-m-d H:i:s",$period['open_time']);
		$period['end_time'] = date("Y-m-d H:i:s",$period['end_time']);
		echo  json_encode($period);
	}

	/**
	 * 正在直播课程
	 */
	public function actionLiveCourse()
	{

	}

}
